package com.dy.yunying.biz.service.hongbao.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.yunying.api.constant.Constant;
import com.dy.yunying.api.datacenter.vo.NoticeDataReportVO;
import com.dy.yunying.api.dto.hongbao.PopupNoticeDto;
import com.dy.yunying.api.entity.ParentGameArea;
import com.dy.yunying.api.entity.WanGameDO;
import com.dy.yunying.api.entity.hongbao.*;
import com.dy.yunying.api.entity.raffle.RaffleActivity;
import com.dy.yunying.api.entity.sign.SignActivity;
import com.dy.yunying.api.enums.ActivityStatusEnum;
import com.dy.yunying.api.req.NoticeDataReq;
import com.dy.yunying.api.req.hongbao.NoticeSortReq;
import com.dy.yunying.api.req.hongbao.OnlineStatusReq;
import com.dy.yunying.api.req.hongbao.PopupNoticeReq;
import com.dy.yunying.api.req.sign.CommonNoticeReq;
import com.dy.yunying.api.req.sign.SelectCommonNoticeReq;
import com.dy.yunying.api.resp.hongbao.*;
import com.dy.yunying.api.resp.hongbao.CommonNoticeVo;
import com.dy.yunying.api.resp.hongbao.NodeData;
import com.dy.yunying.api.resp.hongbao.NodeParentData;
import com.dy.yunying.api.resp.hongbao.OptionData;
import com.dy.yunying.api.vo.usergroup.UserGroupStatVO;
import com.dy.yunying.api.vo.hongbao.PopupNoticeVo;
import com.dy.yunying.api.vo.usergroup.UserGroupStatVO;
import com.dy.yunying.biz.config.YunYingProperties;
import com.dy.yunying.biz.dao.ads.hongbao.*;
import com.dy.yunying.biz.dao.ads.sign.SignActivityMapper;
import com.dy.yunying.biz.dao.clickhouse3399.impl.NoticeDataDao;
import com.dy.yunying.biz.dao.manage.ParentGameAreaMapper;
import com.dy.yunying.biz.dao.manage.ext.GameDOMapperExt;
import com.dy.yunying.biz.dao.manage.ext.ParentGameDOMapperExt;
import com.dy.yunying.biz.dao.manage.ext.PromotionChannelDOMapperExt;
import com.dy.yunying.biz.dao.manage.ext.WanGameChannelInfoDOMapperExt;
import com.dy.yunying.biz.service.hongbao.PopupNoticeService;
import com.dy.yunying.biz.service.raffle.RaffleActivityService;
import com.dy.yunying.biz.utils.DateUtils;
import com.google.common.collect.Lists;
import com.pig4cloud.pig.admin.api.entity.SysDictItem;
import com.pig4cloud.pig.admin.api.feign.RemoteDictService;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author ：lile
 * @date ：2021/10/26 18:00
 * @description：
 * @modified By：
 */
@Log4j2
@Service("PopupNoticeService")
@RequiredArgsConstructor
public class PopupNoticeServiceImpl extends ServiceImpl<PopupNoticeMapper, PopupNotice> implements PopupNoticeService {

	private final PopupNoticeMapper popupNoticeMapper;

	private final PopupNoticeAreaMapper popupNoticeAreaMapper;

	private final PopupNoticeChannelMapper popupNoticeChannelMapper;

	private final PopupNoticeGameMapper popupNoticeGameMapper;

	private final GameDOMapperExt gameDOMapperExt;

	private final PromotionChannelDOMapperExt promotionChannelDOMapperExt;

	private final WanGameChannelInfoDOMapperExt wanGameChannelInfoDOMapperExt;

	private final ParentGameAreaMapper parentGameAreaMapper;

	private final HbActivityMapper activityMapper;

	private final HbSdkDynamicMenusMapper sdkDynamicMenusMapper;

	private final YunYingProperties yunYingProperties;

	private final ParentGameDOMapperExt parentGameDOMapperExt;

	private final NoticeDataDao noticeDataDao;

	private final RemoteDictService remoteDictService;

	private final SignActivityMapper signActivityMapper;

	private final RaffleActivityService raffleActivityService;

	@Override
	public R addPopupNotice(PopupNoticeDto popupNoticeDto) {
		//  添加基本公告信息
		PopupNotice popupNotice = new PopupNotice();
		BeanUtils.copyProperties(popupNoticeDto, popupNotice);
		popupNotice.setCreateTime(new Date());
		Integer userId = SecurityUtils.getUser().getId();
		// 发布时间
		popupNotice.setPopupTime(new Date());
		popupNotice.setCreateId(userId.longValue());
		popupNotice.setUpdateId(userId.longValue());
		popupNotice.setUpdateTime(new Date());
		popupNotice.setMenuId(3L);
		popupNotice.setMenuCode("10003");
		popupNotice.setMenuCodeIos("11003");
		popupNotice.setMenuTitle("红包");
		popupNotice.setOpenType(1);
		popupNotice.setShowType(1);
		popupNotice.setPopupStatus(2);
		popupNotice.setPushFrequency(1);
		popupNotice.setPushNode(4);
		popupNotice.setPopupOrient(1);
		popupNotice.setPopupSort(0);
		popupNotice.setSourceMold(0);
		if (popupNoticeDto.getPopupType() == 1) {
			popupNotice.setPopupEvent("用户创角成功");
			popupNotice.setPopupStartTime(DateUtils.str2Date(popupNoticeDto.getStartTime(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));
			popupNotice.setPopupEndTime(DateUtils.str2Date(popupNoticeDto.getFinishTime(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));
			popupNotice.setPopupTimes(yunYingProperties.getCommonPopupTimes());
		}
		if (popupNoticeDto.getPopupType() == 2) {
			HbActivity activity = activityMapper.selectById(popupNotice.getSourceId());
			if (null != activity) {
				if (1 == activity.getTimeType()) {
					popupNotice.setPopupStartTime(activity.getStartTime());
					popupNotice.setPopupEndTime(activity.getFinishTime());
				} else if (2 == activity.getTimeType()) {
					popupNotice.setPopupStartTime(activity.getStartTime());
					popupNotice.setPopupEndTime(DateUtils.addDays(activity.getFinishTime(), activity.getValidDays()));
				}
				//popupNotice.setSourceBelongType(activity.getActivityType());
			} else {
				// 活动结束前三天 弹窗
				Date endDate = DateUtils.str2Date(popupNoticeDto.getFinishTime(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
				Date sDate = DateUtils.str2Date(popupNoticeDto.getStartTime(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
				// 日期相减
				int betweenDays = DateUtils.betweenDays(sDate, endDate);
				if (betweenDays >= 3) {
					Date startDate = DateUtils.newDate(endDate, -3);
					popupNotice.setPopupStartTime(startDate);
					popupNotice.setPopupEndTime(endDate);
				} else {
					popupNotice.setPopupStartTime(sDate);
					popupNotice.setPopupEndTime(endDate);
				}
			}
			popupNotice.setPopupEvent("活动结束前72/48/24h");
			popupNotice.setPopupTimes(yunYingProperties.getCommonPopupTimes());
		}
		if (popupNoticeDto.getPopupType() == 3 || popupNoticeDto.getPopupType() == 4) {
			popupNotice.setEventCode(popupNoticeDto.getEventCode());
			popupNotice.setPopupEvent(popupNoticeDto.getPopupEvent());
		}
		popupNoticeMapper.insert(popupNotice);
		// 公告主键
		Long id = popupNotice.getId();
		if (Objects.nonNull(id)) {
			// 添加公告和区服
			this.addPopupNoticeArea(popupNoticeDto, id);
			// 添加公告和游戏
			this.addPopupNoticeGame(popupNoticeDto, id);
			// 添加公告和渠道
			this.addPopupNoticeChannel(popupNoticeDto, id);

			return R.ok();
		} else {
			return R.failed();
		}
	}

	/**
	 * 活动区服、游戏、渠道有变动  公告弹窗也要变动
	 *
	 * @param popupNoticeDto
	 * @return
	 */
	@Override
	public R updatePopupNotice(PopupNoticeDto popupNoticeDto) {
		// 根据此活动id 找到对应的公告id
		// 修改编辑后的 区服、游戏、渠道
		Long sourceId = popupNoticeDto.getId();
		QueryWrapper<PopupNotice> query = new QueryWrapper<PopupNotice>();
		if (Objects.nonNull(sourceId)) {
			query.eq("source_id", sourceId);
		}
		query.eq("deleted", Constant.DEL_NO);
		List<PopupNotice> popupNotices = popupNoticeMapper.selectList(query);
		// 此活动下的公告不为空的时候  修改此活动下公告的区服、游戏、渠道
		if (CollectionUtil.isNotEmpty(popupNotices)) {
			//先修改 公告的开始和结束时
			popupNotices.forEach(data -> {
				// 公告id
				Long id = data.getId();
				PopupNotice popupNotice = new PopupNotice();
				BeanUtils.copyProperties(data, popupNotice);
				if (data.getPopupType() == 1) {
					popupNotice.setPopupStartTime(DateUtils.str2Date(popupNoticeDto.getStartTime(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));
					popupNotice.setPopupEndTime(DateUtils.str2Date(popupNoticeDto.getFinishTime(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));
					popupNotice.setPopupTimes(yunYingProperties.getCommonPopupTimes());
				}
				if (data.getPopupType() == 2) {
					HbActivity activity = activityMapper.selectById(popupNotice.getSourceId());
					if (null != activity) {
						if (1 == activity.getTimeType()) {
							popupNotice.setPopupStartTime(activity.getStartTime());
							popupNotice.setPopupEndTime(activity.getFinishTime());
						} else if (2 == activity.getTimeType()) {
							popupNotice.setPopupStartTime(activity.getStartTime());
							popupNotice.setPopupEndTime(DateUtils.addDays(activity.getFinishTime(), activity.getValidDays()));
						}
					} else {
						// 活动结束前三天 弹窗
						Date endDate = DateUtils.str2Date(popupNoticeDto.getFinishTime(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
						Date sDate = DateUtils.str2Date(popupNoticeDto.getStartTime(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
						// 日期相减
						int betweenDays = DateUtils.betweenDays(sDate, endDate);
						if (betweenDays >= 3) {
							Date startDate = DateUtils.newDate(endDate, -3);
							popupNotice.setPopupStartTime(startDate);
							popupNotice.setPopupEndTime(endDate);
						} else {
							popupNotice.setPopupStartTime(sDate);
							popupNotice.setPopupEndTime(endDate);
						}
					}
					popupNotice.setPopupTimes(yunYingProperties.getCommonPopupTimes());
				}
				if (data.getPopupType() == 3 || data.getPopupType() == 4) {
					popupNotice.setEventCode(data.getEventCode());
					popupNotice.setPopupEvent(data.getPopupEvent());
				}
				Integer userId = SecurityUtils.getUser().getId();
				popupNotice.setUpdateId(userId.longValue());
				popupNotice.setUpdateTime(new Date());
				popupNoticeMapper.update(popupNotice, Wrappers.<PopupNotice>lambdaUpdate().eq(PopupNotice::getId, id));

				// 先删除 之前区服和公告的关系 在添加新区服和公告关系
				popupNoticeAreaMapper.delete(new QueryWrapper<PopupNoticeArea>().eq("notice_id", id));
				// 再新增
				this.addPopupNoticeArea(popupNoticeDto, id);

				// 先删除 之前游戏和公告的关系 在添加新游戏和公告关系
				popupNoticeGameMapper.delete(new QueryWrapper<PopupNoticeGame>().eq("notice_id", id));
				// 再新增
				this.addPopupNoticeGame(popupNoticeDto, id);

				// 先删除 之前渠道和公告的关系 在添加新渠道和公告关系
				popupNoticeChannelMapper.delete(new QueryWrapper<PopupNoticeChannel>().eq("notice_id", id));
				// 再新增
				this.addPopupNoticeChannel(popupNoticeDto, id);
			});
			return R.ok();
		} else {
			return R.ok();
		}
	}

	/**
	 * 删除  公告 并且删除 公告对应的区服、游戏、和渠道
	 *
	 * @param popupNoticeDto
	 * @return
	 */
	@Override
	public R deletePopupNotice(PopupNoticeDto popupNoticeDto) {
		// 公告id
		Long id = popupNoticeDto.getId();
		// 先删除 公告信息
		PopupNotice popupNotice = new PopupNotice();
		popupNotice.setUpdateId(SecurityUtils.getUser().getId().longValue());
		popupNotice.setUpdateTime(new Date());
		int flag = popupNoticeMapper.update(popupNotice, Wrappers.<PopupNotice>lambdaUpdate().eq(PopupNotice::getId, id).set(PopupNotice::getDeleted, 1));
		if (flag > 0) {
			// 再删除区服和公告的关系
			PopupNoticeArea popupNoticeArea = new PopupNoticeArea();
			popupNoticeArea.setUpdateId(SecurityUtils.getUser().getId().longValue());
			popupNoticeArea.setUpdateTime(new Date());
			popupNoticeAreaMapper.update(popupNoticeArea, Wrappers.<PopupNoticeArea>lambdaUpdate().eq(PopupNoticeArea::getNoticeId, id).set(PopupNoticeArea::getDeleted, 1));
			// 删除游戏和公告的关系
			PopupNoticeGame popupNoticeGame = new PopupNoticeGame();
			popupNoticeGame.setUpdateId(SecurityUtils.getUser().getId().longValue());
			popupNoticeGame.setUpdateTime(new Date());
			popupNoticeGameMapper.update(popupNoticeGame, Wrappers.<PopupNoticeGame>lambdaUpdate().eq(PopupNoticeGame::getNoticeId, id).set(PopupNoticeGame::getDeleted, 1));

			// 删除渠道和游戏的关系
			PopupNoticeChannel popupNoticeChannel = new PopupNoticeChannel();
			popupNoticeChannel.setUpdateId(SecurityUtils.getUser().getId().longValue());
			popupNoticeChannel.setUpdateTime(new Date());
			popupNoticeChannelMapper.update(popupNoticeChannel, Wrappers.<PopupNoticeChannel>lambdaUpdate().eq(PopupNoticeChannel::getNoticeId, id).set(PopupNoticeChannel::getDeleted, 1));
			return R.ok();
		}
		return R.failed();
	}

	/**
	 * 查询此活动下的通知记录
	 *
	 * @param popupNoticeReq
	 * @return
	 */
	@Override
	public R queryNotice(PopupNoticeReq popupNoticeReq) {
		Page page = new Page();
		page.setCurrent(popupNoticeReq.getCurrent());
		page.setSize(popupNoticeReq.getSize());
		QueryWrapper<PopupNotice> wrapper = new QueryWrapper<>();
		wrapper.eq("source_id", popupNoticeReq.getId());
		wrapper.eq("deleted", 0);
		//公告类型: 0-通用公告; 1-红包活动公告
		wrapper.eq("source_type", 1);
		IPage<PopupNoticeVo> iPage = this.page(page, wrapper);
		return R.ok(iPage);
	}

	/**
	 * 判断此活动下是否存在 唯一类型的唯一事件
	 *
	 * @param popupNoticeDto
	 * @return
	 */
	@Override
	public PopupNotice isExistsOne(PopupNoticeDto popupNoticeDto) {
		PopupNotice popupNotice = new PopupNotice();
		popupNotice.setSourceId(popupNoticeDto.getSourceId());
		popupNotice.setPopupType(popupNoticeDto.getPopupType());
		if (popupNoticeDto.getPopupType() == 1) {
			popupNotice.setPopupEvent("用户创角成功");
		}
		if (popupNoticeDto.getPopupType() == 2) {
			popupNotice.setPopupEvent("活动结束前72/48/24h");
		}
		if (popupNoticeDto.getPopupType() == 3 || popupNoticeDto.getPopupType() == 4) {
			popupNotice.setPopupEvent(popupNoticeDto.getPopupEvent());
		}
		QueryWrapper<PopupNotice> wrapper = new QueryWrapper<>();
		wrapper.eq("source_id", popupNotice.getSourceId());
		wrapper.eq("popup_type", popupNotice.getPopupType());
		wrapper.eq("popup_event", popupNotice.getPopupEvent());
		wrapper.eq("deleted", 0);
		return popupNoticeMapper.selectOne(wrapper);
	}

	// 添加公告和区服关系
	private void addPopupNoticeArea(PopupNoticeDto popupNoticeDto, Long id) {
		try {
			List<PopupNoticeArea> popupNoticeAreaList = new ArrayList<>();
			if (CollectionUtil.isNotEmpty(popupNoticeDto.getAreaList())) {
				popupNoticeDto.getAreaList().forEach(data -> {
					PopupNoticeArea popupNoticeArea = new PopupNoticeArea();
					popupNoticeArea.setNoticeId(id);
					if (1 == data.length) {
						popupNoticeArea.setPgameId(Long.valueOf(data[0]));
						popupNoticeArea.setAreaRange(1);
					}
					if (2 == data.length) {
						popupNoticeArea.setPgameId(Long.valueOf(data[0]));
						popupNoticeArea.setAreaId(Long.valueOf(data[1]));
						popupNoticeArea.setAreaRange(2);
					}
					popupNoticeArea.setDeleted(0);
					popupNoticeArea.setCreateTime(new Date());
					Integer userId = SecurityUtils.getUser().getId();
					popupNoticeArea.setCreateId(userId.longValue());
					popupNoticeArea.setUpdateId(userId.longValue());
					popupNoticeArea.setUpdateTime(new Date());
					popupNoticeAreaList.add(popupNoticeArea);
				});
				popupNoticeAreaMapper.insertBatchPopupNoticeArea(popupNoticeAreaList);
			}
		} catch (Exception e) {
			log.error("添加公告和区服关系失败：{}", e.getMessage());
		}
	}

	// 添加公告和游戏关系
	private void addPopupNoticeGame(PopupNoticeDto popupNoticeDto, Long id) {
		try {
			List<PopupNoticeGame> popupNoticeGameList = new ArrayList<>();
			if (CollectionUtil.isNotEmpty(popupNoticeDto.getGameList())) {
				popupNoticeDto.getGameList().forEach(data -> {
					PopupNoticeGame popupNoticeGame = new PopupNoticeGame();
					if (1 == data.length) {
						popupNoticeGame.setPgameId(Long.valueOf(data[0]));
						popupNoticeGame.setGameRange(1);
					}
					if (2 == data.length) {
						popupNoticeGame.setPgameId(Long.valueOf(data[0]));
						popupNoticeGame.setChildGameId(Long.valueOf(data[1]));
						popupNoticeGame.setGameRange(2);
					}
					popupNoticeGame.setNoticeId(id);
					popupNoticeGame.setDeleted(0);
					popupNoticeGame.setCreateTime(new Date());
					Integer userId = SecurityUtils.getUser().getId();
					popupNoticeGame.setCreateId(userId.longValue());
					popupNoticeGame.setUpdateId(userId.longValue());
					popupNoticeGame.setUpdateTime(new Date());
					popupNoticeGameList.add(popupNoticeGame);
				});
				popupNoticeGameMapper.insertBatchPopupNoticeGame(popupNoticeGameList);
			}
		} catch (Exception e) {
			log.error("添加公告和游戏关系失败：{}", e.getMessage());
		}
	}

	// 添加公告和渠道关系
	private void addPopupNoticeChannel(PopupNoticeDto popupNoticeDto, Long id) {
		try {
			List<PopupNoticeChannel> popupNoticeChannelList = new ArrayList<>();
			if (CollectionUtil.isNotEmpty(popupNoticeDto.getChannelList())) {
				popupNoticeDto.getChannelList().forEach(data -> {
					PopupNoticeChannel popupNoticeChannel = new PopupNoticeChannel();
					popupNoticeChannel.setNoticeId(id);
					if (1 == data.length) {
						popupNoticeChannel.setParentchl(data[0]);
						popupNoticeChannel.setChannelRange(1);
					}
					if (2 == data.length) {
						popupNoticeChannel.setParentchl(data[0]);
						popupNoticeChannel.setChl(data[1]);
						popupNoticeChannel.setChannelRange(2);
					}
					if (3 == data.length) {
						popupNoticeChannel.setParentchl(data[0]);
						popupNoticeChannel.setChl(data[1]);
						popupNoticeChannel.setAppchl(data[2]);
						popupNoticeChannel.setChannelRange(3);
					}
					popupNoticeChannel.setCreateTime(new Date());
					Integer userId = SecurityUtils.getUser().getId();
					popupNoticeChannel.setCreateId(userId.longValue());
					popupNoticeChannel.setUpdateId(userId.longValue());
					popupNoticeChannel.setUpdateTime(new Date());
					popupNoticeChannel.setDeleted(0);
					popupNoticeChannelList.add(popupNoticeChannel);
				});
				popupNoticeChannelMapper.insertBatchPopupNoticeChannel(popupNoticeChannelList);
			}
		} catch (Exception e) {
			log.error("添加公告和渠道关系失败：{}", e.getMessage());
		}
	}


	@Override
	public Page<CommonNoticeVo> selectCommonNoticePage(Page<PopupNotice> page, QueryWrapper<PopupNotice> query, SelectCommonNoticeReq selectReq) {
		// 构建游戏及区服过滤条件
		if (StringUtils.isNotBlank(selectReq.getParentGameArr()) || StringUtils.isNotBlank(selectReq.getGameArr()) || StringUtils.isNotBlank(selectReq.getAreaArr()) ||
				StringUtils.isNotBlank(selectReq.getParentChannelArr()) || StringUtils.isNotBlank(selectReq.getChildChannelArr())) {
			List<Long> noticeIds = baseMapper.selectRangeNoticeId(selectReq.getParentGameArr(), selectReq.getGameArr(), selectReq.getAreaArr(), selectReq.getParentChannelArr(), selectReq.getChildChannelArr());
			if (CollectionUtils.isNotEmpty(noticeIds)) {
				query.in("id", noticeIds);
			} else {
				query.eq("id", 0);//视为匹配不到
			}
		}
		Page<PopupNotice> noticePage = baseMapper.selectPage(page, query);
		Page<CommonNoticeVo> resultPage = new Page<>(page.getCurrent(), page.getSize());
		if (CollectionUtil.isNotEmpty(noticePage.getRecords())) {
			resultPage.setTotal(noticePage.getTotal());
			resultPage.setCountId(noticePage.getCountId());
			resultPage.setPages(noticePage.getPages());
			List<CommonNoticeVo> resultList = new ArrayList<>();
			List<WanGameDO> gameList = gameDOMapperExt.selectList(new QueryWrapper<WanGameDO>().eq("isdelete", Constant.DEL_NO));
			List<NodeParentData> allParentChannelList = promotionChannelDOMapperExt.selectAllChannel();
			List<NodeParentData> allSubChannelList = wanGameChannelInfoDOMapperExt.selectAllSubNodeList();
			List<ParentGameArea> areaList = parentGameAreaMapper.selectList(new QueryWrapper<>());
			List<NodeData> parentGameList = parentGameDOMapperExt.selectMainGameList();
			List<Long> noticeIdsResult = noticePage.getRecords().stream().map(PopupNotice::getId).collect(Collectors.toList());
			//结果集的渠道范围
			List<PopupNoticeChannel> allActivityChannelList = popupNoticeChannelMapper.selectList(new QueryWrapper<PopupNoticeChannel>().in("notice_id", noticeIdsResult));
			//结果集的游戏范围
			List<PopupNoticeGame> allNoticeGameList = popupNoticeGameMapper.selectList(new QueryWrapper<PopupNoticeGame>().in("notice_id", noticeIdsResult));
			//结果集的区服范围
			List<PopupNoticeArea> allNoticeAreaList = popupNoticeAreaMapper.selectList(new QueryWrapper<PopupNoticeArea>().in("notice_id", noticeIdsResult));
			List<NodeParentData> childChannelList;
			List<NodeParentData> subChannelList;
			List<WanGameDO> childGameList;
			List<ParentGameArea> childAreaList;
			for (PopupNotice notice : noticePage.getRecords()) {
				final CommonNoticeVo vo = JSON.parseObject(JSON.toJSONString(notice), CommonNoticeVo.class);
				List<PopupNoticeChannel> activityChannelList = allActivityChannelList.stream().filter(ac -> ac.getNoticeId().equals(vo.getId())).collect(Collectors.toList());
				if (CollectionUtils.isNotEmpty(activityChannelList)) {
					List<String[]> channelList = new ArrayList<>();
					List<String[]> channelDataList = new ArrayList<>();
					String[] channelArr;
					StringBuilder channelSbStr = new StringBuilder();
					for (PopupNoticeChannel noticeChannel : activityChannelList) {
						if (1 == noticeChannel.getChannelRange()) {
							childChannelList = allParentChannelList.stream().filter(t -> StringUtils.isNotBlank(t.getPId()) && t.getPId().equalsIgnoreCase(noticeChannel.getParentchl())).collect(Collectors.toList());
							if (CollectionUtils.isNotEmpty(childChannelList)) {
								for (NodeParentData childChannel : childChannelList) {
									subChannelList = allSubChannelList.stream().filter(t -> StringUtils.isNotBlank(t.getPId()) && t.getPId().equalsIgnoreCase(childChannel.getNodeId())).collect(Collectors.toList());
									if (CollectionUtils.isNotEmpty(subChannelList)) {
										for (NodeParentData subChannel : subChannelList) {
											channelArr = new String[]{noticeChannel.getParentchl(), childChannel.getNodeId(), subChannel.getNodeId()};
											channelList.add(channelArr);
										}
									} else {
										channelArr = new String[]{noticeChannel.getParentchl(), childChannel.getNodeId()};
										channelList.add(channelArr);
									}
								}
							} else {
								channelArr = new String[]{noticeChannel.getParentchl()};
								channelList.add(channelArr);
							}
							String[] channelDataArr = new String[]{noticeChannel.getParentchl()};
							channelDataList.add(channelDataArr);
							channelSbStr.append(getChannelNameByCode(noticeChannel.getParentchl(), allParentChannelList)).append("(全部)，");
						} else if (2 == noticeChannel.getChannelRange()) {
							subChannelList = allSubChannelList.stream().filter(t -> StringUtils.isNotBlank(t.getPId()) && t.getPId().equals(noticeChannel.getChl())).collect(Collectors.toList());
							if (CollectionUtils.isNotEmpty(subChannelList)) {
								for (NodeParentData childChannel : subChannelList) {
									channelArr = new String[]{noticeChannel.getParentchl(), noticeChannel.getChl(), childChannel.getNodeId()};
									channelList.add(channelArr);
								}
							} else {
								channelArr = new String[]{noticeChannel.getParentchl(), noticeChannel.getChl()};
								channelList.add(channelArr);
							}
							String[] channelDataArr = new String[]{noticeChannel.getParentchl(), noticeChannel.getChl()};
							channelDataList.add(channelDataArr);
							channelSbStr.append(getChannelNameByCode(noticeChannel.getParentchl(), allParentChannelList)).append("-").
									append(getChannelNameByCode(noticeChannel.getChl(), allParentChannelList)).append("(全部)，");
						} else if (3 == noticeChannel.getChannelRange()) {
							channelSbStr.append(getChannelNameByCode(noticeChannel.getParentchl(), allParentChannelList)).append("-").
									append(getChannelNameByCode(noticeChannel.getChl(), allParentChannelList)).append("-").
									append(getSubChannelNameByCode(noticeChannel.getAppchl(), allSubChannelList)).append("，");
							channelArr = new String[]{noticeChannel.getParentchl(), noticeChannel.getChl(), noticeChannel.getAppchl()};
							channelList.add(channelArr);
							String[] channelDataArr = new String[]{noticeChannel.getParentchl(), noticeChannel.getChl(), noticeChannel.getAppchl()};
							channelDataList.add(channelDataArr);
						}
					}
					String channelStr = channelSbStr.toString();
					channelStr = channelStr.substring(0, channelStr.length() - 1);
					vo.setChannelNameStr(channelStr);
					vo.setChannelList(channelList);
					vo.setChannelDataList(channelDataList);
				}
				//游戏范围
				List<PopupNoticeGame> noticeGameList = allNoticeGameList.stream().filter(ac -> ac.getNoticeId().equals(vo.getId())).collect(Collectors.toList());
				if (CollectionUtils.isNotEmpty(noticeGameList)) {
					List<Long[]> gameArrList = new ArrayList<>();
					List<Long[]> gameDataList = new ArrayList<>();
					Long[] gameArr;
					Long[] gameDataArr;
					StringBuilder gameSbStr = new StringBuilder();
					for (PopupNoticeGame noticeGame : noticeGameList) {
						if (1 == noticeGame.getGameRange()) {
							childGameList = gameList.stream().filter(t -> null != t.getPgid() && t.getPgid().equals(noticeGame.getPgameId())).collect(Collectors.toList());
							if (CollectionUtils.isNotEmpty(childGameList)) {
								for (WanGameDO game : childGameList) {
									gameArr = new Long[]{noticeGame.getPgameId(), game.getId()};
									gameArrList.add(gameArr);
									gameSbStr.append(getparentGameById(noticeGame.getPgameId(), parentGameList)).append("-").append(getChildGameById(game.getId(), gameList)).append("，");
								}
							} else {
								gameArr = new Long[]{noticeGame.getPgameId()};
								gameArrList.add(gameArr);
								gameSbStr.append(getparentGameById(noticeGame.getPgameId(), parentGameList)).append("，");
							}
							gameDataArr = new Long[]{noticeGame.getPgameId()};
							gameDataList.add(gameDataArr);
						} else if (2 == noticeGame.getGameRange()) {
							gameSbStr.append(getparentGameById(noticeGame.getPgameId(), parentGameList)).append("-").append(getChildGameById(noticeGame.getChildGameId(), gameList)).append("，");
							gameArr = new Long[]{noticeGame.getPgameId(), noticeGame.getChildGameId()};
							gameArrList.add(gameArr);
							gameDataArr = new Long[]{noticeGame.getPgameId(), noticeGame.getChildGameId()};
							gameDataList.add(gameDataArr);
						}
					}
					String gameStr = gameSbStr.toString();
					gameStr = gameStr.substring(0, gameStr.length() - 1);
					vo.setGameNameStr(gameStr);
					vo.setGameList(gameArrList);
					vo.setGameDataList(gameDataList);
				}
				//游戏区服
				List<PopupNoticeArea> noticeAreaList = allNoticeAreaList.stream().filter(ac -> ac.getNoticeId().equals(vo.getId())).collect(Collectors.toList());
				if (CollectionUtils.isNotEmpty(noticeAreaList)) {
					List<Long[]> areaArrList = new ArrayList<>();
					List<Long[]> areaDataList = new ArrayList<>();
					Long[] areaArr;
					Long[] areaDataArr;
					StringBuilder areaSbStr = new StringBuilder();
					for (PopupNoticeArea noticeArea : noticeAreaList) {
						if (1 == noticeArea.getAreaRange()) {
							childAreaList = areaList.stream().filter(t -> null != t.getParentGameId() && t.getParentGameId().equals(noticeArea.getPgameId())).collect(Collectors.toList());
							if (CollectionUtils.isNotEmpty(childAreaList)) {
								for (ParentGameArea area : childAreaList) {
									areaArr = new Long[]{noticeArea.getPgameId(), area.getAreaId()};
									areaArrList.add(areaArr);
									areaSbStr.append(getparentGameById(noticeArea.getPgameId(), parentGameList)).append("-").append(getAreaById(noticeArea.getPgameId(), area.getAreaId(), areaList)).append("，");
								}
							} else {
								areaArr = new Long[]{noticeArea.getPgameId()};
								areaArrList.add(areaArr);
								areaSbStr.append(getparentGameById(noticeArea.getPgameId(), parentGameList)).append("，");
							}
							areaDataArr = new Long[]{noticeArea.getPgameId()};
							areaDataList.add(areaDataArr);
						} else if (2 == noticeArea.getAreaRange()) {
							areaSbStr.append(getparentGameById(noticeArea.getPgameId(), parentGameList)).append("-").append(getAreaById(noticeArea.getPgameId(), noticeArea.getAreaId(), areaList)).append("，");
							areaArr = new Long[]{noticeArea.getPgameId(), noticeArea.getAreaId()};
							areaArrList.add(areaArr);
							areaDataArr = new Long[]{noticeArea.getPgameId(), noticeArea.getAreaId()};
							areaDataList.add(areaDataArr);
						}
					}
					String areaStr = areaSbStr.toString();
					areaStr = areaStr.substring(0, areaStr.length() - 1);
					vo.setAreaNameStr(areaStr);
					vo.setAreaList(areaArrList);
					vo.setAreaDataList(areaDataList);
				}
				resultList.add(vo);
			}
			resultPage.setRecords(resultList);
		}
		return resultPage;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R addCommonNotice(CommonNoticeReq commonNoticeReq) {
		PopupNotice info = JSON.parseObject(JSON.toJSONString(commonNoticeReq), PopupNotice.class);
		R<PopupNotice> checkData = checkParamByCommonNotice(info, commonNoticeReq);
		if (null != checkData) {
			if (CommonConstants.SUCCESS == checkData.getCode()) {
				info = checkData.getData();
			} else {
				return checkData;
			}
		} else {
			return R.failed("参数校验出错");
		}
		info.setSourceType(0);
		info.setPopupTime(new Date());
		info.setPopupTimes(yunYingProperties.getCommonPopupTimes());
		info.setPopupStatus(ActivityStatusEnum.READY.getStatus());
		info.setCreateTime(new Date());
		info.setCreateId(SecurityUtils.getUser().getId().longValue());
		info.setUpdateTime(new Date());
		info.setUpdateId(SecurityUtils.getUser().getId().longValue());
		baseMapper.insert(info);
		generateGameAndChannelAndAreaByNotice(commonNoticeReq, info.getId());
		return R.ok();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R editCommonNotice(CommonNoticeReq commonNoticeReq) {
		if (null == commonNoticeReq.getId() || commonNoticeReq.getId() <= 0) {
			return R.failed("公告ID不能为空");
		}
		PopupNotice info = baseMapper.selectOne(new QueryWrapper<PopupNotice>().eq("id", commonNoticeReq.getId()).ne("popup_status", ActivityStatusEnum.ACTIVITING.getStatus()));
		if (null == info) {
			return R.failed("当前状态无法进行编辑");
		}
		info = JSON.parseObject(JSON.toJSONString(commonNoticeReq), PopupNotice.class);
		R<PopupNotice> checkData = checkParamByCommonNotice(info, commonNoticeReq);
		if (null != checkData) {
			if (CommonConstants.SUCCESS == checkData.getCode()) {
				info = checkData.getData();
			} else {
				return checkData;
			}
		} else {
			return R.failed("参数校验出错");
		}
		info.setUpdateTime(new Date());
		info.setUpdateId(SecurityUtils.getUser().getId().longValue());
		baseMapper.updateById(info);
		generateGameAndChannelAndAreaByNotice(commonNoticeReq, info.getId());
		return R.ok();
	}

	private R<PopupNotice> checkParamByCommonNotice(PopupNotice info, CommonNoticeReq commonNoticeReq) {
		Date startTime = DateUtils.stringToStartDate(commonNoticeReq.getPopupStartTime(), DateUtils.YYYY_MM_DD_HH_MM_SS);
		if (null == startTime) {
			return R.failed("开始时间不合法");
		}
		info.setPopupStartTime(startTime);
		String userGroup = commonNoticeReq.getUserGroup();
		if (StringUtils.isNotBlank(userGroup) && !StringUtils.isNumeric(userGroup)) {
			return R.failed("请提供正确的用户群组ID");
		}
		info.setUserGroup(userGroup);
		Date finishTime = DateUtils.stringToEndDate(commonNoticeReq.getPopupEndTime(), DateUtils.YYYY_MM_DD_HH_MM_SS);
		if (null == finishTime) {
			return R.failed("结束时间不合法");
		}
		if (finishTime.getTime() <= startTime.getTime()) {
			return R.failed("结束时间不能比开始时间小");
		}
		if (finishTime.getTime() < System.currentTimeMillis()) {
			return R.failed("结束时间不能比当前时间小");
		}
		info.setPopupEndTime(finishTime);
		final Integer pushFrequency = commonNoticeReq.getPushFrequency(), pushNode = commonNoticeReq.getPushNode();
		final String pushInterval = commonNoticeReq.getPushInterval();
		info.setPushFrequency(pushFrequency);
		if (1 == pushFrequency || 2 == pushFrequency || 3 == pushFrequency) {
			if (null == pushNode) {
				return R.failed("请提供正确的推送节点");
			}
			info.setPushNode(pushNode);
		} else {
			info.setPushNode(0);
		}
		if (2 == pushFrequency) {
			int interval;
			if (!StringUtils.isNumeric(pushInterval) || (interval = Integer.parseInt(pushInterval)) < 0 || interval > 999) {
				return R.failed("请提供正确的每天推送间隔，间隔天数范围为0~999");
			}
			info.setPushInterval(pushInterval);
		} else if (3 == pushFrequency) {
			int interval;
			if (StringUtils.isBlank(pushInterval)) {
				return R.failed("请提供正确的每周推送间隔");
			}
			for (String s : pushInterval.split(",")) {
				if (!StringUtils.isNumeric(s) || (interval = Integer.parseInt(s)) < 1 || interval > 7) {
					return R.failed("请提供正确的每周推送间隔");
				}
			}
			info.setPushInterval(pushInterval);
		} else {
			info.setPushInterval("");
		}
		if (1 == commonNoticeReq.getPopupMold()) {
			if (2 == commonNoticeReq.getCloseType()) {
				return R.failed("弹窗时，无法设置倒计时");
			}
		} else if (3 == commonNoticeReq.getPopupMold()) {
			if (StringUtils.isBlank(commonNoticeReq.getPopupTitle()) || StringUtils.isBlank(commonNoticeReq.getPopupMessage())) {
				return R.failed("图文时，标题和内容都不能为空");
			}
			int titleLength = commonNoticeReq.getPopupTitle().trim().length();
			if (titleLength < 1 || titleLength > 20) {
				return R.failed("图文时，标题长度不符");
			}
			int messageLength = commonNoticeReq.getPopupMessage().trim().length();
			if (messageLength < 1 || messageLength > 50) {
				return R.failed("图文时，内容长度不符");
			}
			if (2 == commonNoticeReq.getCloseType()) {
				return R.failed("图文时，无法设置倒计时");
			}
		}
		if (2 == commonNoticeReq.getCloseType()) {//倒计时关闭
			if (null == commonNoticeReq.getCloseTimes() || commonNoticeReq.getCloseTimes() > 60 || commonNoticeReq.getCloseTimes() < 0) {
				return R.failed("倒计时数据不合法");
			}
		}
		if (1 == commonNoticeReq.getOpenType()) {//SDK面板
			if (StringUtils.isBlank(commonNoticeReq.getMenuTitle().trim())) {
				return R.failed("SDK面板菜单不能为空");
			}
			List<HbSdkDynamicMenus> sdkDynamicMenusList = sdkDynamicMenusMapper.selectList(new QueryWrapper<HbSdkDynamicMenus>().eq("menu_title", commonNoticeReq.getMenuTitle()).eq("status", 1).eq("deleted", 0));
			if (CollectionUtils.isNotEmpty(sdkDynamicMenusList)) {
				for (HbSdkDynamicMenus sdkDynamicMenus : sdkDynamicMenusList) {
					if (2 == sdkDynamicMenus.getOsType()) {
						info.setMenuId(sdkDynamicMenus.getId());
						info.setMenuCode(sdkDynamicMenus.getMenuCode());
					} else if (3 == sdkDynamicMenus.getOsType()) {
						info.setMenuCodeIos(sdkDynamicMenus.getMenuCode());
					}
				}
			} else {
				return R.failed("SDK菜单数据无法获取");
			}
			if ("红包".equals(commonNoticeReq.getMenuTitle())) {
				if (null == commonNoticeReq.getSourceBelongType()) {
					return R.failed("红包类型不能为空");
				}
			} else if ("活动".equals(commonNoticeReq.getMenuTitle())) {
				if (null == commonNoticeReq.getSourceMold()) {
					return R.failed("活动类型不能为空");
				}
				if (1 == commonNoticeReq.getSourceMold() || 2 == commonNoticeReq.getSourceMold()){
					if (null == commonNoticeReq.getSourceId()) {
						return R.failed("活动ID不能为空");
					}
					if (1 == commonNoticeReq.getSourceMold()) {
						HbActivity activity = activityMapper.selectById(commonNoticeReq.getSourceId());
						if (null != activity) {
							info.setSourceBelongType(activity.getDynamicTypeId().intValue());
						}
					}
				}
			}
		} else if (2 == commonNoticeReq.getOpenType()) {//内置浏览器
			if (StringUtils.isBlank(commonNoticeReq.getImgUrl().trim())) {
				return R.failed("跳转链接不能为空");
			}
			if (null == commonNoticeReq.getShowType()) {
				return R.failed("链接展示不能为空");
			}
		} else if (3 == commonNoticeReq.getOpenType()) {//外链
			if (StringUtils.isBlank(commonNoticeReq.getImgUrl().trim())) {
				return R.failed("跳转链接不能为空");
			}
		} else if (4 == commonNoticeReq.getOpenType()) {//不跳转

		} else {
			return R.failed("暂不支持该类型");
		}
		return R.ok(info);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R onlineCommonNotice(OnlineStatusReq req) {
		PopupNotice info;
		if (ActivityStatusEnum.ACTIVITING.getStatus().equals(req.getStatus())) {
			info = baseMapper.selectOne(new QueryWrapper<PopupNotice>().eq("id", req.getId()).ne("popup_status", ActivityStatusEnum.ACTIVITING.getStatus()));
			if (null == info) {
				return R.failed("当前状态无法上线");
			}
			if (info.getPopupEndTime().getTime() < System.currentTimeMillis()) {
				return R.failed("结束时间不能比当前时间小");
			}
		} else if (ActivityStatusEnum.CLOSE.getStatus().equals(req.getStatus())) {
			info = baseMapper.selectOne(new QueryWrapper<PopupNotice>().eq("id", req.getId()).eq("popup_status", ActivityStatusEnum.ACTIVITING.getStatus()));
			if (null == info) {
				return R.failed("当前状态无法下线");
			}
		} else {
			return R.failed("操作参数不合法");
		}
		info.setPopupStatus(req.getStatus());
		info.setUpdateTime(new Date());
		info.setUpdateId(SecurityUtils.getUser().getId().longValue());
		baseMapper.updateById(info);
		return R.ok();
	}

	@Override
	public void noticeFinish() {
		List<PopupNotice> list = baseMapper.selectList(new QueryWrapper<PopupNotice>().eq("popup_status", ActivityStatusEnum.ACTIVITING.getStatus()).le("popup_end_time", DateUtils.getcurrentTime()));
		if (CollectionUtils.isNotEmpty(list)) {
			for (PopupNotice notice : list) {
				notice.setPopupStatus(ActivityStatusEnum.CLOSE.getStatus());
				notice.setUpdateTime(new Date());
				baseMapper.updateById(notice);
			}
		}
	}

	@Override
	public List<String> selectSdkDynamicMenusTitleList() {
		return sdkDynamicMenusMapper.selectMenuTitleGroupTitle();
	}

	@Override
	public R countNoticeDataTotal(NoticeDataReq req) {
		return R.ok(noticeDataDao.countNoticeDataTotal(req));
	}

	@Override
	public List<OptionData> selectActityListByType(Integer type) {
		List<OptionData> list = new ArrayList<OptionData>();
		if (1 == type) {
			List<HbActivity> activityList = activityMapper.selectList(new QueryWrapper<HbActivity>().eq("activity_status", ActivityStatusEnum.ACTIVITING.getStatus()).ge("DATE_FORMAT(DATE_ADD(finish_time,INTERVAL valid_days DAY),'%Y-%m-%d %H:%i:%S')", DateUtils.getcurrentTime()).orderByDesc("id"));
			if (CollectionUtils.isNotEmpty(activityList)) {
				list = activityList.stream().map(activity -> {
					OptionData od = new OptionData();
					od.setId(activity.getId());
					od.setName(activity.getActivityName());
					return od;
				}).collect(Collectors.toList());
			}
		} else if (2 == type) {
			List<SignActivity> activityList = signActivityMapper.selectList(new QueryWrapper<SignActivity>().eq("activity_status", ActivityStatusEnum.ACTIVITING.getStatus()).ge("DATE_FORMAT(finish_time,'%Y-%m-%d %H:%i:%S')", DateUtils.getcurrentTime()).orderByDesc("id"));
			if (CollectionUtils.isNotEmpty(activityList)) {
				list = activityList.stream().map(activity -> {
					OptionData od = new OptionData();
					od.setId(activity.getId());
					od.setName(activity.getActivityName());
					return od;
				}).collect(Collectors.toList());
			}
		} else if (4 == type) {
			List<RaffleActivity> activityList = raffleActivityService.list(Wrappers.<RaffleActivity>lambdaQuery()
					.eq(RaffleActivity::getActivityStatus, 2)
					.eq(RaffleActivity::getDeleted, 0)
					.orderByDesc(RaffleActivity::getId));
			if (CollectionUtils.isNotEmpty(activityList)) {
				list = activityList.stream().map(activity -> {
					OptionData od = new OptionData();
					od.setId(activity.getId());
					od.setName(activity.getActivityName());
					return od;
				}).collect(Collectors.toList());
			}
		}
		return list;
	}

	@Override
	public List<MenusVO> selectSdkDynamicMenusTitleListByParentId(Long id) {
		return sdkDynamicMenusMapper.selectMenuTitleByParentId(id);
	}

	@Override
	public List<UserGroupStatVO> countWithUserGroupIds(List<Long> userGroupIds) {
		return popupNoticeMapper.countWithUserGroupIds(userGroupIds); // 查询数据
	}

	@Override
	public List<Long> getNoticeIdsWithUserGroupId(Long userGroupId) {
		return popupNoticeMapper.getNoticeIdsWithUserGroupId(userGroupId);
	}

	@Override
	public List<NoticeDataReportVO> selectNoticeDataSource(NoticeDataReq req) {
		List<NoticeDataReportVO> resultData = noticeDataDao.selectNoticeDataReport(req); // 查询数据
		//处理报表数据
		deal(resultData);
		return resultData;
	}

	private void deal(List<NoticeDataReportVO> resultList) {
		if (CollectionUtils.isNotEmpty(resultList)) {
			List<Long> noticeIds = resultList.stream().map(NoticeDataReportVO::getNoticeId).distinct().collect(Collectors.toList());
			//结果集的渠道范围
			List<PopupNotice> allPopupNoticeList = popupNoticeMapper.selectListByIds(noticeIds);
			List<WanGameDO> gameList = gameDOMapperExt.selectList(new QueryWrapper<WanGameDO>().eq("isdelete", Constant.DEL_NO));
			List<NodeParentData> allParentChannelList = promotionChannelDOMapperExt.selectAllChannel();
			List<NodeData> parentGameList = parentGameDOMapperExt.selectMainGameList();
			List<SysDictItem> pushNodeItemList = this.getDict("notice_push_node");
			List<SysDictItem> popupMoldItemList = this.getDict("notice_popup_mold");
			for (NoticeDataReportVO data : resultList) {
				for (PopupNotice popupNotice : allPopupNoticeList) {
					if (popupNotice.getId().equals(data.getNoticeId())) {
						data.setPushNode(popupNotice.getPushNode());
						data.setPopupMold(popupNotice.getPopupMold());
						data.setPopupContent(popupNotice.getPopupContent());
					}
				}
				if (StringUtils.isNotBlank(data.getParentchl())) {
					data.setParentchlname(getChannelNameByCode(data.getParentchl(), allParentChannelList));
				}
				if (StringUtils.isNotBlank(data.getChl())) {
					data.setChlName(getChannelNameByCode(data.getChl(), allParentChannelList));
				}
				if (null != data.getPgid() && data.getPgid() > 0) {
					data.setParentGameName(getparentGameById(data.getPgid(), parentGameList));
				}
				if (null != data.getGameid() && data.getGameid() > 0) {
					data.setGameName(getChildGameById(data.getGameid(), gameList));
				}
				if (null != data.getPopupMold() && data.getPopupMold() > 0) {
					data.setPopupMoldName(getItemLableByValue(data.getPopupMold(), popupMoldItemList));
				}
				if (null != data.getPushNode() && data.getPushNode() > 0) {
					data.setPushNodeName(getItemLableByValue(data.getPushNode(), pushNodeItemList));
				}
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R sortCommonNotice(NoticeSortReq req) {
		PopupNotice popupNotice = baseMapper.selectById(req.getId());
		if (null == popupNotice) {
			return R.failed("数据不存在");
		}
		popupNotice.setPopupSort(req.getSort());
		baseMapper.updateById(popupNotice);
		return R.ok();
	}

	@Override
	public List<NodeParentData> selectChannel(String pId) {
		List<NodeParentData> allParentChannelList = promotionChannelDOMapperExt.selectAllChannel();
		if ("0".equals(pId)) {
			return allParentChannelList.stream().filter(n -> StringUtils.isBlank(n.getPId())).collect(Collectors.toList());
		} else {
			return allParentChannelList.stream().filter(n -> StringUtils.isNotBlank(n.getPId()) && n.getPId().equals(pId)).collect(Collectors.toList());
		}
	}

	/**
	 * @description: 维护公告关系表
	 * @author yuwenfeng
	 * @date 2021/12/2 15:10
	 */
	private void generateGameAndChannelAndAreaByNotice(CommonNoticeReq commonNoticeReq, Long noticeId) {
		if (CollectionUtils.isNotEmpty(commonNoticeReq.getChannelList())) {
			popupNoticeChannelMapper.delete(new QueryWrapper<PopupNoticeChannel>().eq("notice_id", noticeId));
			PopupNoticeChannel noticeChannel;
			for (String[] channelArr : commonNoticeReq.getChannelList()) {
				if (channelArr.length > 0) {
					noticeChannel = new PopupNoticeChannel();
					noticeChannel.setNoticeId(noticeId);
					if (1 == channelArr.length) {
						noticeChannel.setParentchl(channelArr[0]);
						noticeChannel.setChannelRange(1);
					}
					if (2 == channelArr.length) {
						noticeChannel.setParentchl(channelArr[0]);
						noticeChannel.setChl(channelArr[1]);
						noticeChannel.setChannelRange(2);
					}
					if (3 == channelArr.length) {
						noticeChannel.setParentchl(channelArr[0]);
						noticeChannel.setChl(channelArr[1]);
						noticeChannel.setAppchl(channelArr[2]);
						noticeChannel.setChannelRange(3);
					}
					noticeChannel.setCreateTime(new Date());
					noticeChannel.setCreateId(SecurityUtils.getUser().getId().longValue());
					noticeChannel.setUpdateTime(new Date());
					noticeChannel.setUpdateId(SecurityUtils.getUser().getId().longValue());
					popupNoticeChannelMapper.insert(noticeChannel);
				}
			}
		}
		if (CollectionUtils.isNotEmpty(commonNoticeReq.getGameList())) {
			popupNoticeGameMapper.delete(new QueryWrapper<PopupNoticeGame>().eq("notice_id", noticeId));
			PopupNoticeGame noticeGame;
			for (String[] gameArr : commonNoticeReq.getGameList()) {
				if (gameArr.length > 0) {
					noticeGame = new PopupNoticeGame();
					noticeGame.setNoticeId(noticeId);
					if (1 == gameArr.length) {
						noticeGame.setPgameId(Long.valueOf(gameArr[0]));
						noticeGame.setGameRange(1);
					}
					if (2 == gameArr.length) {
						noticeGame.setPgameId(Long.valueOf(gameArr[0]));
						noticeGame.setChildGameId(Long.valueOf(gameArr[1]));
						noticeGame.setGameRange(2);
					}
					noticeGame.setCreateTime(new Date());
					noticeGame.setCreateId(SecurityUtils.getUser().getId().longValue());
					noticeGame.setUpdateTime(new Date());
					noticeGame.setUpdateId(SecurityUtils.getUser().getId().longValue());
					popupNoticeGameMapper.insert(noticeGame);
				}
			}
		}
		if (CollectionUtils.isNotEmpty(commonNoticeReq.getAreaList())) {
			popupNoticeAreaMapper.delete(new QueryWrapper<PopupNoticeArea>().eq("notice_id", noticeId));
			PopupNoticeArea noticeArea;
			for (String[] areaArr : commonNoticeReq.getAreaList()) {
				noticeArea = new PopupNoticeArea();
				noticeArea.setNoticeId(noticeId);
				if (1 == areaArr.length) {
					noticeArea.setPgameId(Long.valueOf(areaArr[0]));
					noticeArea.setAreaRange(1);
				}
				if (2 == areaArr.length) {
					noticeArea.setPgameId(Long.valueOf(areaArr[0]));
					noticeArea.setAreaId(Long.valueOf(areaArr[1]));
					noticeArea.setAreaRange(2);
				}
				noticeArea.setCreateTime(new Date());
				noticeArea.setCreateId(SecurityUtils.getUser().getId().longValue());
				noticeArea.setUpdateTime(new Date());
				noticeArea.setUpdateId(SecurityUtils.getUser().getId().longValue());
				popupNoticeAreaMapper.insert(noticeArea);
			}
		}
	}

	private String getItemLableByValue(Integer value, List<SysDictItem> dictItemList) {
		if (CollectionUtils.isNotEmpty(dictItemList)) {
			for (SysDictItem item : dictItemList) {
				if (item.getValue().equals(value.toString())) {
					return item.getLabel();
				}
			}
		}
		return "";
	}

	private String getAreaById(Long parentGameId, Long areaId, List<ParentGameArea> areaList) {
		if (CollectionUtils.isNotEmpty(areaList)) {
			for (ParentGameArea area : areaList) {
				if (parentGameId.equals(area.getParentGameId()) && areaId.equals(area.getAreaId())) {
					return area.getAreaName();
				}
			}
		}
		return "";
	}

	private String getChildGameById(Long id, List<WanGameDO> gameList) {
		if (CollectionUtils.isNotEmpty(gameList)) {
			for (WanGameDO game : gameList) {
				if (id.equals(game.getId())) {
					return game.getGname();
				}
			}
		}
		return "";
	}

	private String getparentGameById(Long id, List<NodeData> parentGameList) {
		if (CollectionUtils.isNotEmpty(parentGameList)) {
			for (NodeData node : parentGameList) {
				if (id.toString().equals(node.getNodeId())) {
					return node.getNodeName();
				}
			}
		}
		return "";
	}

	private String getChannelNameByCode(String code, List<NodeParentData> parentCahnnelList) {
		if (CollectionUtils.isNotEmpty(parentCahnnelList)) {
			for (NodeParentData node : parentCahnnelList) {
				if (code.equalsIgnoreCase(node.getNodeId())) {
					return node.getNodeName();
				}
			}
		}
		return "";
	}

	private String getSubChannelNameByCode(String code, List<NodeParentData> subCahnnelList) {
		if (CollectionUtils.isNotEmpty(subCahnnelList)) {
			for (NodeParentData node : subCahnnelList) {
				if (code.equalsIgnoreCase(node.getNodeId())) {
					return node.getNodeName();
				}
			}
		}
		return "";
	}

	private List<SysDictItem> getDict(String type) {
		R<List<SysDictItem>> dict = remoteDictService.getDictByType4Inner(SecurityConstants.FROM_IN, type);
		if (dict != null) {
			if (dict.getCode() == 0 && com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(dict.getData())) {
				return dict.getData();
			}
		}
		return Lists.newArrayList();
	}
}
